<template>
  <div class="chartPage-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <summary-view
          title="数据总览"
          :summaryList="dataOverviewList"
          @select="toDetails"
        >
          <XmDatePicker
            initializeType="YYYY-MM-DD"
            type="daterange"
            v-model="timeRang"
            disabledDateT="after"
            label="选择开始时间:"
            prop="fillingTime"
            :config="{ clearable: false, isUrLink: true }"
          ></XmDatePicker>
          <el-button type="primary" @click="timeChange(timeRang)">
            确定
          </el-button>
          <el-button type="primary" @click="exportXlsx">
            导出统计分析数据
          </el-button>
        </summary-view>
      </el-col>
      <el-col :span="24">
        <summary-view
          title="概要"
          :summaryList="summaryList"
          @select="toDetails"
        ></summary-view>
      </el-col>

      <el-col :span="12">
        <area-opening-rate @select="toDetails"></area-opening-rate>
      </el-col>
      <el-col :span="12">
        <diagnostic-statistics @select="toDetails"></diagnostic-statistics>
      </el-col>
      <el-col :span="12">
        <patient-opening-rate @select="toDetails"></patient-opening-rate>
      </el-col>

      <el-col :span="12">
        <age-distribution @select="toDetails"></age-distribution>
      </el-col>
      <el-col :span="12">
        <asthma-inducement @select="toDetails"></asthma-inducement>
      </el-col>

      <el-col :span="12">
        <treatment-level-view @select="toDetails"></treatment-level-view>
      </el-col>

      <el-col>
        <hospitalStaff :timeRang="timeRang" @select="toDetails"></hospitalStaff>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
  import summaryView from '../components/summaryView/index.vue'
  import { useStatisticsXlsx } from '../hooks/useStatisticsXlsx'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import XmDatePicker from '@/components/XMC/XmDatePicker/index.vue'
  import { onMounted, ref, watch } from 'vue'
  import PatientOpeningRate from '../components/patientOpeningRate/index.vue'
  import TreatmentLevelView from '../components/treatmentLevelView/index.vue'
  // eslint-disable-next-line max-len
  import DiagnosticStatistics from '../components/diagnosticStatistics/index.vue'
  import AgeDistribution from '../components/ageDistribution/index.vue'
  import AsthmaInducement from '../components/asthmaInducement/inde.vue'
  import hospitalStaff from '../components/hospitalStaff/index.vue'
  import areaOpeningRate from '../components/areaOpeningRate/index.vue'
  import { useRouter } from 'vue-router'
  import type { Router } from 'vue-router'
  import moment from 'moment'
  import { useStore } from 'vuex'
  import { computed } from '@vue/reactivity'
  import NumberViewComp from '../components/numberViewComp/index.vue'
  import common from '@/utils/common'
  import { cloneDeep } from 'lodash'
  import { isHas } from '@/utils/validate'
  const yesterdayToAll = moment().subtract(1, 'day')
  const yesterday = moment(yesterdayToAll).format('YYYY-MM-DD')
  const timeRang = ref([yesterday, yesterday])
  // const timeRang = ref(['2022-01-01', '2022-12-31'])
  const store = useStore()
  const router = useRouter() as Router
  onMounted(() => {
    console.log('chartPages onMounted')
  })
  onMountedOrActivated(() => {
    // loadData(timeRang.value)
  })
  async function loadData(timeRang: any) {
    const startDay = timeRang[0]
    const endDay = timeRang[1]
    const promise1 = store.dispatch('statistics/updateLocalSummary', {
      startDay,
      endDay,
    })
    const promise2 = store.dispatch('statistics/updateLocalDataOverview', {
      startDay,
      endDay,
    })
    const promise3 = store.dispatch('statistics/updateLocalMarkedRate', {
      startDay,
      endDay,
    })
    const promise4 = store.dispatch('statistics/updateLocalBottomData', {
      startDay,
      endDay,
    })
    const promise5 = store.dispatch('statistics/updateLocalHospitalStaffs', {
      startDay,
      endDay,
      pageIndex: 0,
      pageSize: 10,
    })

    common.XmLoading(true)
    Promise.all([promise1, promise2, promise3, promise4, promise5])
      .then((res) => {
        console.log('Promise.all1')
        common.XmLoading(false)
      })
      .catch((err) => {
        common.XmLoading(false)
        common.XmMessage(1, '加载失败，请重试')
      })
  }

  function timeChange(val: string[]) {
    loadData(val)
  }

  // timeRang更新其他接口也要更新
  watch(
    () => timeRang.value,
    (val) => {
      console.log('val =' + JSON.stringify(timeRang.value))
      timeChange(val)
    },
    { immediate: true }
  )

  const summaryList = computed(() => {
    // return store.getters.summaryList
    let list = cloneDeep(store.getters.summaryList)
    if (Array.isArray(list) && isHas(store.getters.markedCard.marked)) {
      let markedWithIndex: number = -1
      const value = store.getters.markedCard.marked
      list.forEach((element: any, index: number) => {
        if (element.name === '打卡数') {
          markedWithIndex = index
          element.value = value
        }
      })
      if (markedWithIndex === -1) {
        list = list.concat([{ name: '打卡数', value }])
      }
    }
    return list
  })

  const dataOverviewList = computed(() => {
    let list = cloneDeep(store.getters.overviewList)
    if (
      Array.isArray(store.getters.overviewList) &&
      isHas(store.getters.markedCard.visitRate)
    ) {
      let visitRateWithIndex: number = -1
      const value = (store.getters.markedCard.visitRate * 100).toFixed(2) + '%'
      // TODO any后期要改动
      list.forEach((element: any, index: number) => {
        if (element.name === '累计复诊率') {
          visitRateWithIndex = index
          element.value = value
        }
      })
      if (visitRateWithIndex === -1) {
        list = list.concat([{ name: '累计复诊率', value }])
      }
    }
    if (
      Array.isArray(store.getters.overviewList) &&
      isHas(store.getters.diagnosed)
    ) {
      let diagnosedWithIndex: number = -1
      const value = store.getters.diagnosed
      list.forEach((element: any, index: number) => {
        if (element.name === '累计确诊人数') {
          diagnosedWithIndex = index
          element.value = value
        }
      })
      if (diagnosedWithIndex === -1) {
        list = list.concat([{ name: '累计确诊人数', value }])
      }
    }
    return list
  })

  const diagnosed = computed(() => {
    return store.getters.diagnosed
  })

  const marked = computed(() => {
    return store.getters.markedCard.marked
  })

  const visitRate = computed(() => {
    return store.getters.markedCard.visitRate
  })

  const toDetails = function (query: { name: string }) {
    console.log('toDetails =' + JSON.stringify(query))
    const startDay = timeRang.value[0]
    const endDay = timeRang.value[1]
    const encode = {
      ...query,
      startDay,
      endDay,
      name: encodeURIComponent(query.name),
    }
    router.push({ name: 'chartDetails', query: encode })
  }
  function exportXlsx() {
    const startDay = timeRang.value[0]
    const endDay = timeRang.value[1]
    const fileName = `${startDay}~${endDay}数据统计文档.xlsx`
    useStatisticsXlsx(fileName)
  }
</script>

<script lang="ts">
  export default {
    name: 'chartPage',
  }
</script>
<style lang="scss" scoped>
  .chartPage-container {
    padding: 32px;
  }
</style>
